<template>
	<view class="container">
		<view class="ipt" style="margin-top: 30rpx;">
			<text>手机号码</text>
			<input maxlength="11" type="number" placeholder="请输入手机号码" v-model="mobile"/>
		</view>
		<view class="code-container ipt">
			<view>
				<text>验证码</text>
				<view v-if="!checkCodeFlag" @click="handleSendCode">发送验证码</view>
				<view v-if="checkCodeFlag" style="color: #9B9B9B;border: none;font-size: 14px;">已发送（{{ count }}S）</view>
			</view>
			<input maxlength="6" type="number" placeholder="请输入验证码" v-model="checkCode"/>
		</view>
		<view class="submit" @click="handleConfirmBindMobile">确认绑定</view>
		<view class="modal" :class="modalFlag ? 'show' : ''">
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				modalFlag: false, // 默认模态框为关闭状态
				openId: '', // 用户openId
				mobile: '',//手机号码
				checkCodeFlag: false, // 判断是否发生验证码
				checkCode: "", // 手机验证码
				count: 60, // 验证码数字判断
				id: '',//第三方授权id
				loginType: 1,//1微信登录,2苹果登陆
				oldCheckCode: '',//旧的验证码，防止误触登录
				inviteCode: '',
				register_obj: {},//微信或苹果的信息
			}; 
		},
		methods: {
			// 验证手机号格式是否正确
			checkLoginNameFormat(mobile) {
				let reg = /^[1][3456789][0-9]{9}$/
				if (!reg.test(mobile)) {
				  uni.showToast({ title: '手机号格式不正确', icon: 'none' })
				  return false
				}
				return true
			},
			// 发送验证码
			async handleSendCode () {
				if (!this.checkLoginNameFormat(this.mobile)) return 
				this.checkCodeFlag = true
				const mobile = this.$jsencrypt.setEncrypt(this.$api.publicKey, this.mobile);
				let res = await this.$fetch(this.$api.mobile_verification_code, { length: 6, mobile }, 'POST')
				if (res.code) return uni.showToast({ title: res.msg, icon: 'none' })
				this.timer = setInterval(() => {
				  if (this.count === 0) {
				    clearInterval(this.timer)
					this.checkCodeFlag = false
					this.count = 60
				  }
				  this.count = --this.count
				}, 1000)
			},
			
			// 点击确认绑定
			async handleConfirmBindMobile() {
				console.log('获取区域绑定手机region前6', uni.getStorageSync('region').slice(0, 6))
				if (!this.checkCode.trim()) return uni.showToast({ title: '请先输入验证码~', icon: 'none' })
				if (!this.mobile.trim()) return uni.showToast({ title: '请输入手机号码~', icon: 'none' })
				// 防止误触登陆按钮
				// if(this.oldCheckCode == this.checkCode) return uni.showToast({ title: '请输入新验证码~', icon: 'none' })
				// this.oldCheckCode = this.checkCode
				
				var pinf = plus.push.getClientInfo()
				var cid = pinf.clientid//客户端标识  
				let adcode = uni.getStorageSync('region').slice(0, 6)
				let obj = {
					// avatarUrl: this.register_obj.avatar, 
					checkCode: this.checkCode, // 验证码
					cid: cid,//客户端标识  
					id: this.id,
					loginType: this.loginType,
					mobile: this.mobile,
					nickName:  this.register_obj.userName ,
					adcode: adcode,
				} 
				console.log('信息',obj)
				// return
				let res = await this.$fetch(this.$api.register, obj, 'POST')//
				
				if (res.code) return uni.showToast({ title: res.msg, icon: 'none' })
				uni.setStorageSync('token', res.data.token)
				if(this.register_obj.sex) {
					// 微信性别0保密1男2女，找零工0男1女
					this.sex = this.register_obj.sex == 1 ? 0 : 1
					// this.upd_user(this.sex)
				}
				
				uni.showToast({ title: '登录成功~', icon: 'none' })
				// 是否已注册
				this.getUserInfo()
				this.get_current_location()
			},
			// 获取用户当前的经纬度
			get_current_location() {
				uni.getLocation({
				    type: 'gcj02',
				    success: (res)=> {
						uni.setStorageSync('location', [res.latitude,res.longitude ])
						this.getAdcode(res.latitude, res.longitude)
				    }
				})
			},
			// 由经纬度查询街道的行政代码
			getAdcode (lat, lng) {
				uni.request({
					url: 'https://restapi.amap.com/v3/geocode/regeo?parameters',
					data: {
						key: 'd73cc951a96637a251a9a2446b48ce9c',
						location: lng + ',' + lat 
					},
					success: res => {
						let region = res.data.regeocode.addressComponent.towncode.slice(0, 9)
						uni.setStorageSync('region', region)
						console.log('获取区域region', uni.getStorageSync('region'))
						if(uni.getStorageSync('token')) {
							this.upd_user(lat, lng, region,this.sex)//修改	
						}
					}
				})
			},
			//更新用户位置
			async upd_user (lat, lng, region,sex) {
				//经纬度保留6位小数
				lat = lat.toFixed(6) 
				lng = lng.toFixed(6) 
				region = region.slice(0, 9)
				console.log('更新用户位置', lat, lng, region)
				let res = await this.$fetch(this.$api.upd_user, {lat: lat, lng: lng, region: region,sex: sex } , 'POST')
				console.log('更新用户位置res',res)
			},
			
			// 获取当前用户信息
			async getUserInfo () {
				let res = await this.$fetch(this.$api.get_current_user, {}, 'GET')
				if(res.data.payPwdFlag){
					uni.setStorageSync('isHavePayPassword',true)
				}
				else{
					uni.setStorageSync('isHavePayPassword',false)
				}
				// if (res.code) return uni.showToast({ title: res.msg, icon: 'none' })
				if (res.code===531) {
					uni.navigateTo({
						url: '/pages/riskControl/riskControl',
					})
					return
				}
				console.log('用户',res.data.userType)
				// 注册用户
				if(res.data.userType == '-1' ) {
					console.log('未注册')
					setTimeout(() => { uni.reLaunch({ url: '/pages/select-identity/select-identity' }) }, 600)
				// 登录用户
				}
	// 			else if(res.data.user.avatarto == null  && res.data.user.avatar=="FqbM4OLbmiUwDDB984eZl5lJudxS" && (res.data.cid==''||res.data.cid=='0')){
	// 	// <!-- 此处改动， 154-158
	// // 第一次登录  设置个人信息
	// 				setTimeout(() => { uni.switchTab({ url: '/pages/userifo-supplement/userifo-supplement' }) }, 600)
	// 			}
				else{
					console.log('已经注册')
					uni.setStorageSync("level",res.data.user.level)//用户等级
					setTimeout(() => { uni.switchTab({ url: '/pages/index/index' }) }, 600)
				}
			},
			
			
		},
		onLoad(options) {  
			this.id = options.id
			this.loginType = options.loginType
			this.register_obj = uni.getStorageSync('register_obj')
		}
	}
</script>

<style lang="less">
.container {
	overflow: hidden;
	
	& > view.ipt {
		background: #FFFFFF;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		
		input {
			font-size: 14px;
			text-align: right;
		}
	}
	
	& > .code-container {
		position: relative;
		
		&::before {
			content: "";
			position: absolute;
			width: 720rpx;
			height: 1px;
			left: 30rpx;
			top: 0;
			background: #F3F3F3;
		}
		
		& > view:first-child {
			display: flex;
			align-items: center;
			
			text {
				margin-right: 30rpx;
			}
			
			view {
				padding: 8rpx;
				// border: 1px solid #FCC928;
				border-radius: 4px;
				font-size: 10px;
				color: #F39B19;
			}
		}
	}
	
	& > .submit {
		position: fixed;
		bottom: 0;
		left: 0;
		background: #FCC928;
		width: 100vw;
		height: 100rpx;
		padding: 0;
		justify-content: center;
		display: flex;
		align-items: center;
		
		&:active {
			opacity: 0.7;
		}
	}
}

.modal {
	position: fixed;
	top: 0;
	right: 0;
	bottom: 0;
	left: 0;
	z-index: 1110;
	opacity: 0;
	outline: 0;
	text-align: center;
	-ms-transform: scale(1.185);
	transform: scale(1.185);
	backface-visibility: hidden;
	perspective: 2000upx;
	background: rgba(0, 0, 0, 0.6);
	transition: all 0.3s ease-in-out 0s;
	pointer-events: none;
	
	&.show {
		opacity: 1;
		transition-duration: 0.3s;
		-ms-transform: scale(1);
		transform: scale(1);
		overflow-x: hidden;
		overflow-y: auto;
		pointer-events: auto;
	}
	
	.main {
		position: fixed;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		width: 516rpx;
		border-radius: 10rpx; 
		padding: 30rpx;
		background: #FFFFFF;
		position: relative;
		
		image {
			width: 516rpx;
			height: 516rpx;
		}
		
		.text {
			color: #848484;
			margin-top: 5rpx;
		}
		
		.handle {
			color: #45b6e0;
			margin-top: 30rpx;
			line-height: 14px;
		}
		
		&::before {
			content: "";
			position: absolute;
			width: 100%;
			height: 1px;
			background: #f7f7f7;
			bottom: calc(60rpx + 14px);
			left: 0;
		}
	}
}
</style>
